package com.solutionsfit.timesheet.action

import static org.jboss.seam.annotations.FlushModeType.MANUAL
import static org.jboss.seam.ScopeType.CONVERSATION

import org.jboss.seam.faces.FacesMessages
import javax.persistence.Query
import com.solutionsfit.timesheet.Project
import com.solutionsfit.timesheet.PayPeriodType
import com.solutionsfit.timesheet.GroovyTimesheet
import com.solutionsfit.timesheet.User
import org.jboss.seam.annotations.Create
import org.jboss.seam.annotations.Begin
import org.jboss.seam.annotations.End
import org.jboss.seam.annotations.Name
import org.jboss.seam.annotations.In
import org.jboss.seam.annotations.Out
import org.jboss.seam.annotations.Factory
import org.jboss.seam.annotations.Logger
import org.jboss.seam.annotations.Scope
import org.jboss.seam.annotations.datamodel.DataModel
import org.jboss.seam.annotations.datamodel.DataModelSelection
import org.jboss.seam.log.Log

import javax.persistence.EntityManager

@Name("editProject")
@Scope(CONVERSATION)
class EditProjectAction {
	@Logger
	Log log
	
	@In
	FacesMessages facesMessages
	
	@In
	EntityManager em
	
	@DataModel(value="projects")
	List<Project> projects
	
	@DataModelSelection(value="projects")
	Project projectSelection
	
	@In(required=false) @Out(required=false)
	Project project
	
	@DataModel(value="users")
	List<User> users
	
	List<Long> userIds
	
	@Factory("projects")
	@Begin(flushMode=MANUAL)
	void loadProjects() {
		projects = em.createQuery("select project from Project as project").resultList
	}
	
	@Factory("users")
	void loadUsers() {
		users = em.createQuery("select user from User as user").resultList
	}
	
	String select() {
		project = projectSelection
		
		userIds = new ArrayList<Long>()
		
		project.users.each {
			userIds << it.id
		}
		
		"/projectEdit.xhtml"
	}
	
	@End
	String saveProject() {
		project.users.clear()
		
		userIds.each {
			project << em.find(User.class, it)
		}
		
		em.flush()
		
		facesMessages.add("Modified project: #0", project.name)
		
		"/projects.xhtml"
	}
}